import React from 'react';
import { Alert, Button } from 'antd';

class ErrorBoundary extends React.Component {
  state = { hasError: false, error: null, errorInfo: null };

  static getDerivedStateFromError(error) {
    return { hasError: true, error };
  }

  componentDidCatch(error, errorInfo) {
    this.setState({ errorInfo });
    console.error('Error caught by boundary:', error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return (
        <div style={{ 
          padding: 24, 
          textAlign: 'center',
          maxWidth: 800,
          margin: '0 auto'
        }}>
          <Alert 
            message="系统错误" 
            description={
              <div>
                <p>抱歉，发生了意外错误，请刷新页面重试。</p>
                {process.env.NODE_ENV === 'development' && (
                  <details style={{ 
                    textAlign: 'left', 
                    marginTop: 10,
                    color: '#666'
                  }}>
                    <summary>错误详情</summary>
                    <p>{this.state.error?.toString()}</p>
                    <pre style={{ 
                      whiteSpace: 'pre-wrap',
                      wordWrap: 'break-word',
                      fontSize: 12
                    }}>
                      {this.state.errorInfo?.componentStack}
                    </pre>
                  </details>
                )}
              </div>
            } 
            type="error" 
            showIcon
            style={{ marginBottom: 20 }}
          />
          <Button 
            type="primary" 
            onClick={() => window.location.reload()}
          >
            刷新页面
          </Button>
        </div>
      );
    }
    return this.props.children; 
  }
}

export default ErrorBoundary;